<template>
  <div class="training-progress-page">
    <h3 class="page-title">培训进度</h3>

    <!-- 培训项目列表 -->
    <div
      v-for="(item, index) in trainingItems"
      :key="index"
      class="training-item"
    >
      <div class="item-header">
        <span class="name">{{ item.name }}</span>
        <span class="project">{{ item.project }}</span>
        <span class="date">{{ item.date }}</span>
      </div>

      <div class="progress-steps">
        <!-- 步骤1：报名 -->
        <div class="step-item">
          <div
            :class="[
              'step-circle',
              { 'step-done': item.steps[0].status === 'done' },
              { 'step-active': item.steps[0].status === 'active' },
              { 'step-pending': item.steps[0].status === 'pending' }
            ]"
          >
            1
          </div>
          <div class="step-label">{{ item.steps[0].label }}</div>
          <div class="step-status">{{ item.steps[0].statusText }}</div>
          <el-button
            v-if="item.steps[0].button"
            type="text"
            size="small"
            @click="handleButtonClick(0, item)"
          >
            {{ item.steps[0].button }}
          </el-button>
        </div>

        <!-- 步骤1-2连接线 -->
        <div
          :class="[
            'step-connector',
            { 'connector-done': item.steps[0].status === 'done' }
          ]"
        ></div>

        <!-- 步骤2：培训 -->
        <div class="step-item">
          <div
            :class="[
              'step-circle',
              { 'step-done': item.steps[1].status === 'done' },
              { 'step-active': item.steps[1].status === 'active' },
              { 'step-pending': item.steps[1].status === 'pending' }
            ]"
          >
            2
          </div>
          <div class="step-label">{{ item.steps[1].label }}</div>
          <div class="step-status">{{ item.steps[1].statusText }}</div>
          <el-button
            v-if="item.steps[1].button"
            type="text"
            size="small"
            @click="handleButtonClick(1, item)"
          >
            {{ item.steps[1].button }}
          </el-button>
        </div>

        <!-- 步骤2-3连接线 -->
        <div
          :class="[
            'step-connector',
            { 'connector-done': item.steps[1].status === 'done' }
          ]"
        ></div>

        <!-- 步骤3：考试 -->
        <div class="step-item">
          <div
            :class="[
              'step-circle',
              { 'step-done': item.steps[2].status === 'done' },
              { 'step-active': item.steps[2].status === 'active' },
              { 'step-pending': item.steps[2].status === 'pending' }
            ]"
          >
            3
          </div>
          <div class="step-label">{{ item.steps[2].label }}</div>
          <div class="step-status">{{ item.steps[2].statusText }}</div>
          <el-button
            v-if="item.steps[2].button"
            type="text"
            size="small"
            @click="handleButtonClick(2, item, 'button')"
          >
            {{ item.steps[2].button }}
          </el-button>
          <el-button
            v-if="item.steps[2].extraButton"
            type="text"
            size="small"
            @click="handleButtonClick(2, item, 'extraButton')"
          >
            {{ item.steps[2].extraButton }}
          </el-button>
        </div>

        <!-- 步骤3-4连接线 -->
        <div
          :class="[
            'step-connector',
            { 'connector-done': item.steps[2].status === 'done' }
          ]"
        ></div>

        <!-- 步骤4：取证 -->
        <div class="step-item">
          <div
            :class="[
              'step-circle',
              { 'step-done': item.steps[3].status === 'done' },
              { 'step-active': item.steps[3].status === 'active' },
              { 'step-pending': item.steps[3].status === 'pending' }
            ]"
          >
            4
          </div>
          <div class="step-label">{{ item.steps[3].label }}</div>
          <div class="step-status">{{ item.steps[3].statusText }}</div>
          <el-button
            v-if="item.steps[3].button"
            type="text"
            size="small"
            @click="handleButtonClick(3, item, 'button')"
          >
            {{ item.steps[3].button }}
          </el-button>
          <el-button
            v-if="item.steps[3].extraButton"
            type="text"
            size="small"
            @click="handleButtonClick(3, item, 'extraButton')"
          >
            {{ item.steps[3].extraButton }}
          </el-button>
        </div>
      </div>
    </div>

    <!-- 空状态提示 -->
    <div v-if="trainingItems.length === 0" class="empty-state">
      <el-empty description="暂无培训记录"></el-empty>
    </div>

    <!-- 详情弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      :width="dialogWidth"
      center
      destroy-on-close
    >
      <div class="dialog-content">
        <!-- 报名详情 -->
        <template v-if="dialogType === 'signup'">
          <!-- 修复：column="1" 改为 column=1（数字类型） -->
          <el-descriptions column=1 border>
            <el-descriptions-item label="项目名称">{{ dialogData.projectMap || '-' }}</el-descriptions-item>
            <el-descriptions-item label="报名时间">{{ formatDate(dialogData.createTime) || '-' }}</el-descriptions-item>
            <el-descriptions-item label="提交状态">{{ getSubmitStatusText(dialogData.submitStatus) }}</el-descriptions-item>
            <el-descriptions-item label="支付状态">{{ getPaymentStatusText(dialogData.paymentStatus) }}</el-descriptions-item>
            <el-descriptions-item label="所属单位">{{ dialogData.unitName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ dialogData.phonenumber || '-' }}</el-descriptions-item>
            <el-descriptions-item label="工作简历">{{ dialogData.workResume || '-' }}</el-descriptions-item>
          </el-descriptions>
        </template>

        <!-- 培训详情 -->
        <template v-if="dialogType === 'training'">
          <el-descriptions column=1 border>
            <el-descriptions-item label="培训班名称">{{ dialogData.trainingClassName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="培训类型">{{ dialogData.trainingType === '2' ? '线上培训' : '线下培训' }}</el-descriptions-item>
            <el-descriptions-item label="开始时间">{{ formatDate(dialogData.startDate) || '-' }}</el-descriptions-item>
            <el-descriptions-item label="结束时间">{{ formatDate(dialogData.endDate) || '-' }}</el-descriptions-item>
            <el-descriptions-item label="培训地点">{{ dialogData.trainingAddress || '-' }}</el-descriptions-item>
            <el-descriptions-item label="培训状态">{{ getClassStatusText(dialogData.classStatus) }}</el-descriptions-item>
            <el-descriptions-item label="班主任">{{ dialogData.headTeacher1 || '-' }}</el-descriptions-item>
            <el-descriptions-item label="总名额">{{ dialogData.totalQuota || '-' }}</el-descriptions-item>
          </el-descriptions>
        </template>

        <!-- 考试详情 -->
        <template v-if="dialogType === 'exam'">
          <el-descriptions column=1 border>
            <el-descriptions-item label="考试安排ID">{{ dialogData.examScheduleId || '-' }}</el-descriptions-item>
            <el-descriptions-item label="开始时间">{{ formatDate(dialogData.examStartTime) || '待安排' }}</el-descriptions-item>
            <el-descriptions-item label="结束时间">{{ formatDate(dialogData.examEndTime) || '待安排' }}</el-descriptions-item>
            <el-descriptions-item label="考试时长">{{ dialogData.examDuration ? dialogData.examDuration + '分钟' : '-' }}</el-descriptions-item>
            <el-descriptions-item label="考试地点">{{ dialogData.examLocation || '-' }}</el-descriptions-item>
            <el-descriptions-item label="考试状态">{{ getExamStatusText(dialogData.examStatus) }}</el-descriptions-item>
            <el-descriptions-item label="及格分数">{{ dialogData.examPassScore ? dialogData.examPassScore + '分' : '-' }}</el-descriptions-item>
          </el-descriptions>
        </template>

        <!-- 成绩详情 -->
        <template v-if="dialogType === 'examResult'">
          <el-descriptions column=1 border>
            <el-descriptions-item label="考试项目">{{ dialogData.projectMap || '-' }}</el-descriptions-item>
            <el-descriptions-item label="考试时间">
              {{ dialogData.examRecordList && dialogData.examRecordList[0]
                ? formatDate(dialogData.examRecordList[0].examTime)
                : '未考试' }}
            </el-descriptions-item>
            <el-descriptions-item label="考试成绩">
              {{ dialogData.examRecordList && dialogData.examRecordList[0]
                ? (dialogData.examRecordList[0].score || '待公布')
                : '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="考试状态">{{ getExamStatusText(dialogData.examStatus) }}</el-descriptions-item>
            <el-descriptions-item label="及格分数">
              {{ dialogData.examSchedule && dialogData.examSchedule.examPassScore
                ? dialogData.examSchedule.examPassScore + '分'
                : '-' }}
            </el-descriptions-item>
          </el-descriptions>
        </template>

        <!-- 证书详情 -->
        <template v-if="dialogType === 'certificate'">
          <el-descriptions column=1 border>
            <el-descriptions-item label="证书类型">{{ dialogData.certificateType === '1' ? '特种设备作业人员证' : '-' }}</el-descriptions-item>
            <el-descriptions-item label="作业类别">{{ dialogData.workCategory || '-' }}</el-descriptions-item>
            <el-descriptions-item label="作业项目">{{ dialogData.workProject || '-' }}</el-descriptions-item>
            <el-descriptions-item label="证书编号">{{ dialogData.certificateNo || '待生成' }}</el-descriptions-item>
            <el-descriptions-item label="有效期开始">{{ formatDate(dialogData.validityStartTime) || '-' }}</el-descriptions-item>
            <el-descriptions-item label="有效期结束">{{ formatDate(dialogData.validityEndTime) || '-' }}</el-descriptions-item>
            <el-descriptions-item label="发证机关">{{ dialogData.issuingAuthority || '-' }}</el-descriptions-item>
            <el-descriptions-item label="审核状态">{{ getCertReviewStatusText(dialogData.reviewStatus) }}</el-descriptions-item>
          </el-descriptions>
        </template>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button
          type="primary"
          v-if="dialogType === 'certificate' && dialogData.certificateStatus === '3'"
          @click="downloadCertificate(dialogData.specialCertificateId)"
        >
          下载电子证书
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTrainingProgress } from "@/api/training/registration";

export default {
  name: 'TrainingProgressPage',
  data() {
    return {
      trainingItems: [],
      dialogVisible: false,
      dialogTitle: '',
      dialogData: null,
      dialogType: '',
      dialogWidth: '600px',
      total:"",
      pageSize:"",
      pageCurrage:"",
    }
  },
  created() {
    this.getTrainingProgressList();
  },
  methods: {
    async getTrainingProgressList() {
      try {
        const studentId = this.$store.state.user.studentId;
        if (!studentId) {
          this.$message.warning('请先登录');
          return;
        }

        const response = await listTrainingProgress(studentId);
        if (response.code === 200 && Array.isArray(response.rows)) {
          this.trainingItems = response.rows.map(item => this.formatItemData(item));
        } else {
          this.trainingItems = [];
          this.$message.info('暂无培训记录');
        }
      } catch (error) {
        console.error('获取培训进度失败:', error);
        this.$message.error('加载失败，请刷新页面重试');
      }
    },

    formatItemData(row) {
      const regProgress = row.registrationProgress || {};
      const classProgress = row.classStudentProgress || {};
      const examProgress = row.examProgress || {};
      const certProgress = row.certificateProgress || {};
      const regDto = regProgress.registrationDto || {};
      const trainingClass = classProgress.trainingClass || {};

      return {
        name: regDto.studentName || '未知学员',
        project: regDto.projectMap || '未知项目',
        date: this.formatDate(trainingClass.startDate) || '未知日期',
        originalData: row,
        steps: [
          this.formatSignupStep(regDto),
          this.formatTrainingStep(trainingClass),
          this.formatExamStep(examProgress),
          this.formatCertificateStep(certProgress)
        ]
      };
    },

    formatSignupStep(regDto) {
      let status, statusText;
      if (regDto.paymentStatus === '1') {
        status = 'done';
        statusText = '已报名';
      } else if (regDto.submitStatus === '1') {
        status = 'active';
        statusText = '待付款';
      } else if (regDto.submitStatus === '0') {
        status = 'pending';
        statusText = '未提交';
      } else {
        status = 'pending';
        statusText = '未报名';
      }
      return { label: '报名', status, statusText, button: '查看详情' };
    },

    formatTrainingStep(trainingClass) {
      let status, statusText;
      switch (trainingClass.classStatus) {
        case '2':
          status = 'active';
          statusText = '培训中';
          break;
        case '3':
          status = 'done';
          statusText = '已完成';
          break;
        case '1':
          status = 'pending';
          statusText = '未开始';
          break;
        default:
          status = 'pending';
          statusText = '未知状态';
      }
      return { label: '培训', status, statusText, button: '查看详情' };
    },

    formatExamStep(examProgress) {
      let status, statusText;
      switch (examProgress.examStatus) {
        case '2':
          status = 'active';
          statusText = '考试中';
          break;
        case '3':
          status = 'done';
          statusText = '已完成';
          break;
        case '1':
          status = 'done';
          statusText = '已报考';
          break;
        default:
          status = 'pending';
          statusText = '未报考';
      }
      return {
        label: '考试',
        status,
        statusText,
        button: '查看详情',
        extraButton: examProgress.examStatus === '3' ? '查询成绩' : null
      };
    },

    formatCertificateStep(certProgress) {
      let status, statusText;
      switch (certProgress.certificateStatus) {
        case '3':
          status = 'done';
          statusText = '已取证';
          break;
        case '2':
          status = 'active';
          statusText = '审核中';
          break;
        case '1':
          status = 'done';
          statusText = '已申请';
          break;
        default:
          status = 'pending';
          statusText = '未申请';
      }
      return {
        label: '取证',
        status,
        statusText,
        button: '查看详情',
        extraButton: certProgress.certificateStatus === '3' ? '下载证书' : null
      };
    },

    handleButtonClick(stepIndex, item, buttonType = 'button') {
      const originalData = item.originalData;
      switch (stepIndex) {
        case 0:
          this.dialogType = 'signup';
          this.dialogTitle = '报名详情';
          this.dialogData = originalData.registrationProgress?.registrationDto || {};
          break;
        case 1:
          this.dialogType = 'training';
          this.dialogTitle = '培训详情';
          this.dialogData = originalData.classStudentProgress?.trainingClass || {};
          break;
        case 2:
          if (buttonType === 'button') {
            this.dialogType = 'exam';
            this.dialogTitle = '考试详情';
            this.dialogData = {
              ...originalData.examProgress || {},
              ...originalData.examProgress?.examSchedule || {}
            };
          } else {
            this.dialogType = 'examResult';
            this.dialogTitle = '成绩查询';
            this.dialogData = originalData.examProgress || {};
          }
          break;
        case 3:
          this.dialogType = 'certificate';
          this.dialogTitle = buttonType === 'button' ? '证书详情' : '下载电子证书';
          this.dialogData = {
            ...originalData.certificateProgress || {},
            ...originalData.certificateProgress?.specialCertificate || {}
          };
          break;
      }
      this.dialogVisible = true;
    },

    downloadCertificate(certId) {
      if (!certId) {
        this.$message.warning('证书ID不存在');
        return;
      }
      console.log('下载证书ID:', certId);
      this.$message.success('电子证书已开始下载');
    },

    formatDate(dateStr) {
      if (!dateStr) return '';
      try {
        const date = new Date(dateStr);
        if (isNaN(date.getTime())) return dateStr;
        return date.toLocaleDateString('zh-CN');
      } catch (error) {
        return dateStr;
      }
    },

    getSubmitStatusText(status) {
      const map = { '0': '未提交', '1': '已提交' };
      return map[status] || '未知';
    },
    getPaymentStatusText(status) {
      const map = { '0': '未支付', '1': '已支付' };
      return map[status] || '未知';
    },
    getClassStatusText(status) {
      const map = { '1': '未开始', '2': '进行中', '3': '已结束' };
      return map[status] || '未知';
    },
    getExamStatusText(status) {
      const map = { '1': '已报考', '2': '考试中', '3': '已完成' };
      return map[status] || '未报考';
    },
    getCertReviewStatusText(status) {
      const map = { '0': '待审核', '1': '审核通过', '2': '审核驳回' };
      return map[status] || '未知';
    }
  }
}
</script>

<style scoped>
/* 样式保持不变 */
.training-progress-page {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  min-height: 300px;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  color: #303133;
}

.training-item {
  margin-bottom: 25px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f2f3f5;
}
.training-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.item-header {
  font-size: 16px;
  margin-bottom: 15px;
  padding-bottom: 8px;
  border-bottom: 1px dashed #eee;
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  color: #606266;
}
.item-header .name {
  color: #303133;
  font-weight: 500;
}
.item-header .project {
  flex: 1;
  min-width: 200px;
  word-break: break-all;
}

.progress-steps {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  overflow: auto;
  padding: 10px 0;
}

.step-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 120px;
  flex-shrink: 0;
  padding: 0 5px;
}

.step-circle {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-weight: bold;
  margin-bottom: 8px;
  transition: all 0.3s ease;
}
.step-done {
  background-color: #409EFF;
}
.step-active {
  background-color: #409EFF;
  box-shadow: 0 0 0 4px rgba(64, 158, 255, 0.2);
}
.step-pending {
  background-color: #C0C4CC;
}

.step-label {
  font-size: 14px;
  color: #303133;
  margin-bottom: 4px;
  text-align: center;
}
.step-status {
  font-size: 12px;
  color: #606266;
  margin-bottom: 8px;
  text-align: center;
}

.step-connector {
  height: 2px;
  background-color: #C0C4CC;
  flex-grow: 1;
  margin: 0 10px;
  transition: background-color 0.3s ease;
}
.connector-done {
  background-color: #409EFF;
}

.empty-state {
  padding: 60px 0;
  text-align: center;
}

.dialog-content {
  max-height: 500px;
  overflow-y: auto;
  padding-right: 10px;
}
.dialog-footer {
  text-align: center;
}

@media (max-width: 768px) {
  .training-progress-page {
    padding: 15px 10px;
  }

  .item-header {
    gap: 10px;
    font-size: 14px;
  }

  .progress-steps {
    flex-direction: column;
    align-items: flex-start;
    padding-left: 20px;
  }

  .step-connector {
    width: 2px;
    height: 30px;
    margin: 0 0 0 15px;
    align-self: flex-start;
  }

  .step-item {
    flex-direction: row;
    min-width: auto;
    gap: 10px;
    margin-bottom: 10px;
    align-items: center;
  }

  .step-circle {
    margin-bottom: 0;
  }

  .el-dialog {
    width: 90% !important;
  }
}
</style>
